<template>
  <div class="card">
    <!-- 头部 -->
    <div class="header">
      <!-- 全局搜索 -->
      <div class="child">
        <InputGroup style="width: 300px;">
          <InputText placeholder="全局搜索，拼命开发中" />
          <Button icon="pi pi-search" severity="warning" @click="tempbtn()" />
        </InputGroup>
      </div>
      <div class="child center">
        <Dropdown v-model="optioncode" :options="options" showClear optionLabel="name"
          placeholder="选择分组" style="width: 300px; max-width: 300px;" />
      </div>
      <div class="child">
        <Button icon="pi pi-plus" label="添加短链" severity="info" @click="addShort()" :loading="addshortisloading" />  
        <Button icon="pi pi-refresh" label="Reload" severity="warning"
          :loading="store.state.AllShorts.isloading" @click="getAllLinks()" style="margin-left: 1rem;" />
      </div>
    </div>
    <!-- 内容 -->
    <div class="container">
      <div class="header">
        <div class="link">链接</div>
        <div class="note">备注</div>
        <div class="count">计数</div>
        <div class="action">操作</div>
      </div>
      <div class="table">
        <ShortCard v-for="(item) of filteredData" :key="item.id" :item="item" @deleteshort="deleteshort">
        </ShortCard>
      </div>
    </div>
  </div>
  <!-- 消息提示 -->
  <Toast />
  <!-- 确认框 -->
  <ConfirmDialog></ConfirmDialog>
  <!-- 添加信息框 -->
  <Dialog v-model:visible="dialogvisible" modal header="添加长链" :style="{ width: '45rem' }">
    <span class="p-text-secondary block mb-5">输入长链信息</span>
    <div class="flex align-items-center gap-3 mb-3">
      <label for="username" class="font-semibold w-6rem">链接</label>
      <InputText id="username" class="flex-auto" autocomplete="off" v-model="linkLong" />
    </div>
    <div class="flex align-items-center gap-3 mb-5">
      <label for="email" class="font-semibold w-6rem">备注</label>
      <InputText id="email" class="flex-auto" autocomplete="off" v-model="linkNote" />
    </div>
    <div class="flex justify-content-end gap-2">
      <Button type="button" label="Cancel" severity="secondary" @click="dialogvisible = false"></Button>
      <Button type="button" label="Save" @click="toaddlong()"></Button>
    </div>
  </Dialog>
</template>

<script setup>
import InputText from 'primevue/inputtext';
import Button from 'primevue/button';
import InputGroup from 'primevue/inputgroup';
import InputGroupAddon from 'primevue/inputgroupaddon';
import Dropdown from 'primevue/dropdown';
import ShortCard from './ShortCard.vue'
import { provide, ref, onMounted, computed } from 'vue';
import Dialog from 'primevue/dialog';

// 弹窗组件，给子组件用
import ConfirmDialog from 'primevue/confirmdialog';
import { useConfirm } from "primevue/useconfirm";
import { useToast } from "primevue/usetoast";

import axios from 'axios';

import { useStore } from 'vuex';

const store = useStore();

function getAllLinks() {
  store.dispatch('getAllShorts')
}

onMounted(() => {
  store.dispatch('getGroupShortLink')
})

const addshortisloading = ref(false)
// 添加短链
function addShort(){
  addshortisloading.value = true
  axios.post("https://api.cxkqun.com/index.php/api/short/short", {
    'auth': 'cxkqun',
    'action': 'create'
  }).then(res => {
    if(res.data.code){
      toast.add({ severity: 'info', summary: '添加成功', detail: `成功添加短链：https://cxkqun.xyz/${res.data.data.short_code}`, life: 3000 });
      store.dispatch('getAllShorts')
    }else{
      toast.add({ severity: 'info', summary: '添加失败', detail: `添加短链失败`, life: 3000 });
    }
    addshortisloading.value = false
  })
}

// 分组
const options = computed(() => store.state.GroupShortLink.map(group => ({
  name: group.group_name,
  code: group.id
})));

const optioncode = ref(); // 假设optioncode的初始结构

const filteredData = computed(() => {
  // 首先检查optioncode.value.code是否存在
  if (optioncode.value && optioncode.value.code) {
    // 根据optioncode.value.code从GroupShortLink中找到对应的group
    const group = store.state.GroupShortLink.find(item => item.id === optioncode.value.code);

    // 检查是否找到了group，并且这个group有groupshort属性
    if (group && Array.isArray(group.groupshort)) {
      // 获取group的groupshort数组中所有对象的short_code
      const shortCodes = group.groupshort.map(gs => gs.short_code);

      // 使用这些short_code来过滤AllShorts.data
      return store.state.AllShorts.data.filter(item => shortCodes.includes(item.short_code));
    }
  }
  // 如果optioncode.value.code不存在，或者找不到对应的group，或group没有groupshort属性，返回所有数据
  return store.state.AllShorts.data;
});




function tempbtn() {
  console.log(options)
}


// 删除短链函数->给子组件
const confirm = useConfirm();
const toast = useToast();
const deleteshort = (data) => {
  confirm.require({
    message: `确认删除短链：https://cxkqun.xyz/${data.short_code}吗？`,
    header: '短链删除确认',
    icon: 'pi pi-info-circle',
    rejectLabel: '取消',
    acceptLabel: '删除',
    rejectClass: 'p-button-secondary p-button-outlined',
    acceptClass: 'p-button-danger',
    accept: () => {
      axios.post("https://api.cxkqun.com/index.php/api/short/short", {
        'auth': 'cxkqun',
        'action': 'delete',
        'shortCode': data.short_code
      }).then(res => {
        if (res.data.code) {
          toast.add({ severity: 'info', summary: '删除成功', detail: `https://cxkqun.xyz/${data.short_code}已被删除`, life: 3000 });
        } else {
          toast.add({ severity: 'error', summary: '删除失败', detail: `https://cxkqun.xyz/${data.short_code}未被删除`, life: 3000 });
        }
        store.dispatch('getAllShorts')
      })

    },
    reject: () => {
      toast.add({ severity: 'error', summary: '取消删除', detail: 'You have rejected', life: 3000 });
    }
  });
};

// 修改短链备注
const editshort = (data) => {
  axios.post("https://api.cxkqun.com/index.php/api/short/short", {
    'auth': 'cxkqun',
    'action': 'update',
    'shortCode': data.short_code,
    'note': data.note
  }).then(res => {
    if (res.data.code) {
      toast.add({ severity: 'info', summary: '修改成功', detail: `备注已修改为：${data.note}`, life: 3000 });
    } else {
      toast.add({ severity: 'error', summary: '修改失败', detail: `备注修改失败`, life: 3000 });
    }
    store.dispatch('getAllShorts')
  })
}

// 长链删除函数
const deletelong = (data) => {
  confirm.require({
    message: `确认删除长链：${data.original_url}吗？`,
    header: '长链删除确认',
    icon: 'pi pi-info-circle',
    rejectLabel: '取消',
    acceptLabel: '删除',
    rejectClass: 'p-button-secondary p-button-outlined',
    acceptClass: 'p-button-danger',
    accept: () => {
      axios.post("https://api.cxkqun.com/index.php/api/short/long", {
        'auth': 'cxkqun',
        'action': 'delete',
        'shortCode': data.short_code,
        'id': data.id
      }).then(res => {
        if (res.data.code) {
          toast.add({ severity: 'info', summary: '删除成功', detail: `${data.original_url}已被删除`, life: 3000 });
        } else {
          toast.add({ severity: 'error', summary: '删除失败', detail: `${data.original_url}删除失败`, life: 3000 });
        }
        store.dispatch('getAllShorts')
      })
    },
    reject: () => {
      toast.add({ severity: 'error', summary: '取消删除', detail: 'You have rejected', life: 3000 });
    }
  });
};

// 添加长链
const dialogvisible = ref(false);
const linkLong = ref();
const linkNote = ref();
const short_code = ref()
const addlong = (data) => {
  short_code.value = data.short_code
  dialogvisible.value = !dialogvisible.value
}
const toaddlong = (data) => {
  // 输入不规范
  if (!isValidURL(linkLong.value)) {
    toast.add({ severity: 'error', summary: '格式错误', detail: '请输入正确的链接', life: 3000 });
  } else {
    axios.post("https://api.cxkqun.com/index.php/api/short/long", {
      'auth': 'cxkqun',
      'action': 'create',
      'shortCode': short_code.value,
      'originalUrl': linkLong.value,
      'note': linkNote.value
    }).then(res => {
      if (res.data.code) {
        toast.add({ severity: 'info', summary: '添加成功', detail: `长链：${linkLong.value}添加成功`, life: 3000 });
      } else {
        toast.add({ severity: 'error', summary: '添加失败', detail: `长链：${linkLong.value}添加失败`, life: 3000 });
      }
      dialogvisible.value = !dialogvisible.value
      store.dispatch('getAllShorts')
    })
  }
}
// url格式检查
function isValidURL(string) {
  let url;
  try {
    url = new URL(string);
  } catch (_) {
    return false;
  }
  return url.protocol === "http:" || url.protocol === "https:";
}

// 修改长链
const updatelong = (newlong) => {
  if (newlong.long === newlong.oldlong && newlong.note === newlong.oldnote) {
    confirm.require({
      message: `新旧数据相同`,
      header: '无法修改',
      icon: 'pi pi-exclamation-triangle',
      rejectClass: 'p-button-secondary p-button-outlined',
      rejectLabel: '取消',
      acceptLabel: '确认',
    });
    return false;
  }
  if (newlong.long !== newlong.oldlong) {
    confirm.require({
      message: `长链将被修改为：${newlong.long}`,
      header: '修改确认',
      icon: 'pi pi-exclamation-triangle',
      rejectClass: 'p-button-secondary p-button-outlined',
      rejectLabel: '取消',
      acceptLabel: '确认',
      accept: () => {
        if (!isValidURL(newlong.long)) {
          toast.add({ severity: 'error', summary: '格式错误', detail: '请输入正确的链接', life: 3000 });
        } else {
          axios.post("https://api.cxkqun.com/index.php/api/short/long", {
            'auth': 'cxkqun',
            'action': 'update',
            'shortCode': newlong.short_code,
            'id': newlong.id,
            'newUrl': newlong.long,
            'note': newlong.note
          }).then(res => {
            if (res.data.code) {
              toast.add({ severity: 'info', summary: '修改成功', detail: `长链：${newlong.oldlong}修改成功`, life: 3000 });
            } else {
              toast.add({ severity: 'error', summary: '修改失败', detail: `长链：${newlong.oldlong}修改失败`, life: 3000 });
            }
            store.dispatch('getAllShorts')
          })
        }

      },
      reject: () => {
        toast.add({ severity: 'error', summary: '取消修改', detail: 'You have rejected', life: 3000 });
      }
    });
  }

  if (newlong.note !== newlong.oldnote && newlong.long === newlong.oldlong) {
    confirm.require({
      message: `备注将被修改为：${newlong.note}`,
      header: '修改确认',
      icon: 'pi pi-exclamation-triangle',
      rejectClass: 'p-button-secondary p-button-outlined',
      rejectLabel: '取消',
      acceptLabel: '确认',
      accept: () => {
        if (!isValidURL(newlong.long)) {
          toast.add({ severity: 'error', summary: '格式错误', detail: '请输入正确的链接', life: 3000 });
        } else {
          axios.post("https://api.cxkqun.com/index.php/api/short/long", {
            'auth': 'cxkqun',
            'action': 'update',
            'shortCode': newlong.short_code,
            'id': newlong.id,
            'newUrl': newlong.long,
            'note': newlong.note
          }).then(res => {
            if (res.data.code) {
              toast.add({ severity: 'info', summary: '修改成功', detail: `备注已修改为：${newlong.note}`, life: 3000 });
            } else {
              toast.add({ severity: 'error', summary: '修改失败', detail: `修改备注为：${newlong.note}失败`, life: 3000 });
            }
            store.dispatch('getAllShorts')
          })
        }

      },
      reject: () => {
        toast.add({ severity: 'error', summary: '取消修改', detail: 'You have rejected', life: 3000 });
      }
    });
  }
}

// 使用 provide 函数提供函数
provide('deleteshort', deleteshort);
provide('deletelong', deletelong);
provide('addlong', addlong);
provide('updatelong', updatelong);
provide('editshort', editshort)
</script>

<style lang="less" scoped>
.card {
  width: calc(100% - 1rem);
  height: 100%;
  background-color: #fff;
  border: 1px solid #e2e8f0;
  margin-right: 1rem;
  display: flex;
  flex-direction: column;
  background-color: #fff;

  &>.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;

    &>.child {
      flex: 1;
    }

    &>.center {
      flex: 0 0 auto;
    }

    &>:nth-child(3) {
      display: flex;
      justify-content: right;
    }
  }

  &>.container {
    padding: 20px 10px 0 10px;
    background-color: #fff;
    flex: 1;
    height: calc(100% - 32px);
    display: flex;
    flex-direction: column;

    &>.header {
      display: flex;
      position: sticky;
      top: 0;
      /* 表头固定在顶部 */
      z-index: 10;
      /* 确保表头在滚动内容上方 */
      background-color: #fff;
      border-bottom: 1px solid #e2e8f0;

      &>* {
        // flex: 1;
        width: 33%;
        padding-left: 10px;
        line-height: 60px;
        color: #334155;
        font-weight: 600;
      }

      &>.count {
        // flex: 0.5;
        width: 17%;
      }

      &>.action {
        // flex: 0.5;
        width: 17%;
      }
    }

    &>.table {
      flex: 1;
      height: calc(100% - 60px);
      overflow-y: auto;
    }
  }
}
</style>
